package com.pro.addresslist.ui.activity;

import java.util.ArrayList;
import java.util.List;

import android.R.integer;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.pro.addresslist.R;
import com.pro.addresslist.dal.bll.ContactInfoBLL;
import com.pro.addresslist.dal.model.ContactInfo;
import com.pro.addresslist.dal.model.ContactInfoBySqlite;
import com.pro.addresslist.dal.model.IPMAC;
import com.pro.addresslist.sqllite.ContactInfoServise;
import com.pro.addresslist.tools.NetUtil;
import com.pro.addresslist.tools.URLUtil;
import com.pro.addresslist.tools.constantUtil;
import com.pro.addresslist.tools.runNumber;
import com.pro.addresslist.ui.activity.MacAddressActivity.ReciveBroadcast;
import com.pro.addresslist.ui.adapter.CommonAdapter;
import com.pro.addresslist.ui.adapter.ViewHolder;
import com.pro.addresslist.ui.common.BaseActivity;

public class SynchronizeActivity extends BaseActivity {

	private TextView syn_new;
	private TextView syn_update;
	private ListView syn_list;
	private Button syn_uplod;
	private Button syn_downlod;
	private List<ContactInfoBySqlite> list=new ArrayList<ContactInfoBySqlite>();
	private CommonAdapter adapter;
	private int[] srcImg={R.drawable.label_new,R.drawable.label_edit,R.drawable.label_delete};
	private List<ContactInfo> listCon=new ArrayList<ContactInfo>();
	private int num=0;
	private List<ContactInfoBySqlite> listAdd=new ArrayList<ContactInfoBySqlite>();
	private List<ContactInfoBySqlite> listUpdata=new ArrayList<ContactInfoBySqlite>();
	private int UpNum=0;
	private int count=0;
	private Boolean state=true;
	@Override
	public int getLayout() {
		// TODO Auto-generated method stub
		return R.layout.synchronize;
	}

	@Override
	public void OnActCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		setTtile("上传与同步");
		setLeftImageBack();
		initView();
		initEvent();
		ReciveBroadcast receive=new ReciveBroadcast();
		IntentFilter filter=new IntentFilter();
		filter.addAction("lbs_AddContact");
		filter.addAction("lbs_UpdataContact");
		filter.addAction("lbs_DelContactByID");
		filter.addAction("lbs_SelectContactByID");
		registerReceiver(receive, filter);
		adapter=new CommonAdapter<ContactInfoBySqlite>(mContext, list, R.layout.syn_item) {
			@Override
			public void convert(ViewHolder holder, ContactInfoBySqlite t) {
				holder.setText(R.id.title, t.get_Name());
				holder.setText(R.id.img, t.get_Name().substring(0, 1));
				int stateImg=0;
				//新增
				if(t.get_State()==1){
					stateImg=srcImg[0];
				}
				//修改
				if(t.get_State()==2){
					stateImg=srcImg[1];
				}
				holder.setImageResource(R.id.state, stateImg);
			}
		};
		syn_list.setAdapter(adapter);
		new Thread(new myThreadstate()).start();
		new Thread(new myThreadstateno()).start();
	}
	void initView(){
		syn_new=(TextView) findViewById(R.id.syn_new);
		syn_update=(TextView) findViewById(R.id.syn_update);
		syn_list=(ListView) findViewById(R.id.syn_list);
		syn_uplod=(Button) findViewById(R.id.syn_uplod);
		syn_downlod=(Button) findViewById(R.id.syn_downlod);
	}
	void initEvent(){
		syn_uplod.setOnClickListener(this);
		syn_downlod.setOnClickListener(this);
	}
	@Override
	public void OnViewClick(View v) {
		switch (v.getId()) {
		case R.id.syn_uplod:
			if(NetUtil.isNetworkAvailable(mContext)){
			if(num!=0){
				state=false;
				for(ContactInfoBySqlite con:listAdd){
					ContactInfo coninfo = writeModel(con);
					ContactInfoBLL.AddContact(mContext, coninfo,con.get_id());
				}
				for(ContactInfoBySqlite con:listUpdata){
					UpNum++;
					ContactInfoBLL.SelectContactByID(mContext, con.get_ContactID(),0);
				}
			}
			else {
				Toast.makeText(mContext, "没有可上传的！", Toast.LENGTH_LONG).show();
			}
			}
			else {
				Toast.makeText(mContext, "当前没有网络哟，请稍后再试！", Toast.LENGTH_LONG).show();
			}
			break;
		case R.id.syn_downlod:
			if(NetUtil.isNetworkAvailable(mContext)){
			if(num==0){
			ContactInfoBLL.SelectContactByAll(mContext, mainHandler);
			showProgressDialog();
			}
			else {
				Toast.makeText(mContext, "本地有修改，请先上传！", Toast.LENGTH_LONG).show();
			}
			}
			else {
				Toast.makeText(mContext, "当前没有网络哟，请稍后再试！", Toast.LENGTH_LONG).show();
			}
			break;
		default:
			break;
		}
	}

	private ContactInfo writeModel(ContactInfoBySqlite con) {
		ContactInfo coninfo=new ContactInfo();
		coninfo.set_Address(con.get_Address()==null?"":con.get_Address());
		coninfo.set_Birthday(con.get_Birthday()==null?"":con.get_Birthday());
		coninfo.set_ContactID(con.get_ContactID()==null?"":con.get_ContactID());
		coninfo.set_DepartAddress(con.get_DepartAddress()==null?"":con.get_DepartAddress());
		coninfo.set_Department(con.get_Department()==null?"":con.get_Department());
		coninfo.set_DepartTell(con.get_DepartTell()==null?"":con.get_DepartTell());
		coninfo.set_Depict(con.get_Depict()==null?"":con.get_Depict());
		coninfo.set_dy(con.get_dy()==null?"":con.get_dy());
		coninfo.set_gk(con.get_gk()==null?"":con.get_gk());
		coninfo.set_FamilyTell(con.get_FamilyTell()==null?"":con.get_FamilyTell());
		coninfo.set_Food(con.get_Food()==null?"":con.get_Food());
		coninfo.set_HeadImage(con.get_HeadImage()==null?"":con.get_HeadImage());
		coninfo.set_Interest(con.get_Interest()==null?"":con.get_Interest());
		coninfo.set_Mobile(con.get_Mobile()==null?"":con.get_MobileEn());
		coninfo.set_Name(con.get_Name()==null?"":con.get_Name());
		coninfo.set_Nationality(con.get_Nationality()==null?"":con.get_Nationality());
		coninfo.set_OtherTell(con.get_OtherTell()==null?"":con.get_OtherTell());
		coninfo.set_Post(con.get_Post()==null?"":con.get_Post());
		coninfo.set_Unit(con.get_Unit()==null?"":con.get_Unit());
		coninfo.set_Sex(con.get_Sex());
		return coninfo;
	}

	private Handler mainHandler=new Handler(){
		public void handleMessage(Message msg){
			super.handleMessage(msg);
			switch (msg.what) {
			case constantUtil.Num_SelectContactByAll:
				listCon=(List<ContactInfo>) msg.obj;
				new Thread(new myThreadConAll()).start();
				break;
				case constantUtil.Num_SelectContactByAll1:
					disMissDialog();
					Toast.makeText(mContext, "同步成功！", Toast.LENGTH_LONG).show();
				    finish();
					break;
				case constantUtil.Num_SelectCountByStateno:
					num=msg.arg1;
					break;
				case constantUtil.Num_SelectCountByState:
					int[] nums=(int[]) msg.obj;
					syn_new.setText(nums[0]+"");
					syn_update.setText(nums[1]+"");
					adapter.notifyDataSetChanged();
					if(state==false){
						Toast.makeText(mContext, "上传成功！", Toast.LENGTH_LONG).show();
					    finish();
					}
					break;
			}
		}
	};
	//查询状态不为0的数量
	class myThreadstateno implements Runnable {
		@Override
		public void run() {
			ContactInfoServise conSer=new ContactInfoServise(mContext);
			int num=conSer.SelectCountByState();
			Message message = new Message();   
	        message.what = constantUtil.Num_SelectCountByStateno;
	        message.arg1=num;
	        mainHandler.sendMessage(message);
		}
	}
	class myThreadstate implements Runnable {
		@Override
		public void run() {
			ContactInfoServise conSer=new ContactInfoServise(mContext);
			listAdd=conSer.SelectCountByState(1);
			listUpdata=conSer.SelectCountByState(2);
			int[] nums={listAdd.size(),listUpdata.size()};
			list.clear();
			for(ContactInfoBySqlite con:listAdd){
				list.add(con);
			}
			for(ContactInfoBySqlite con:listUpdata){
				list.add(con);
			}
			Message message = new Message();   
	        message.what = constantUtil.Num_SelectCountByState;
	        message.obj=nums;
	        mainHandler.sendMessage(message);
		}
	}
	class myThreadConAll implements Runnable {
		@Override
		public void run() {
			ContactInfoServise conSer=new ContactInfoServise(mContext);
			
			Boolean sss=conSer.DelContactAll();
			Log.i("libs", sss+"shan");
			int i=1;
			for(ContactInfo con:listCon){
				Boolean ss=conSer.AddContactdatabase(con);
				Log.i("libs", ss+"jia"+i);
				i++;
			}
			
			Message message = new Message();   
	        message.what = constantUtil.Num_SelectContactByAll1;
	        mainHandler.sendMessage(message);
		}
	}
	public class ReciveBroadcast extends BroadcastReceiver {

		@SuppressLint("NewApi") @Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String  action=intent.getAction();
			final ContactInfoServise conSer=new ContactInfoServise(mContext);
			if(action=="lbs_AddContact"){
				//得到广播中得到的数据，并显示出来 
				 String result = (String) intent.getSerializableExtra("parameter");
				 Integer ID=(Integer) intent.getSerializableExtra("id");
				 if(result.equals("succeed")){
					 conSer.UpdataContactStateByID(ID, 0);
					 new Thread(new myThreadstate()).start();
					 new Thread(new myThreadstateno()).start();
				 }
	    	}
			if(action=="lbs_UpdataContact"){
				String result = (String) intent.getSerializableExtra("parameter");
				Integer ID=(Integer) intent.getSerializableExtra("id");
				if(result.equals("succeed")){
					 conSer.UpdataContactStateByID(ID, 0);
					 new Thread(new myThreadstate()).start();
					 new Thread(new myThreadstateno()).start();
				 }
			}
			if(action=="lbs_DelContactByID"){
				String result = (String) intent.getSerializableExtra("parameter");
				Integer ID=(Integer) intent.getSerializableExtra("id");
				if(result.equals("succeed")){
					 conSer.DelContactByIDTrue(ID);
					 new Thread(new myThreadstate()).start();
					 new Thread(new myThreadstateno()).start();
				 }
	    	}
			if(action=="lbs_SelectContactByID"){
				ContactInfo result = (ContactInfo)intent.getSerializableExtra("parameter");
				final String contactID = (String)intent.getSerializableExtra("contactID");
				int type = (Integer) intent.getSerializableExtra("type");
				if(result.get_ContactID()==null){
					count++;
					int TempNum=listUpdata.size();
					if(UpNum==TempNum){
						String text="检测到 "+count+" 个联系人已被远程数据库删除，是否强制上传？";
						Builder dia = new AlertDialog.Builder(SynchronizeActivity.this)   
						.setMessage(text)  
						.setPositiveButton("是" ,  new OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								conSer.UpdataContactStateByConID(contactID, 1);
								runNumber runNum=new runNumber();
								conSer.UpdataContactIDByConID(runNum.getMaxID(),contactID);
								new Thread(new myThreadstate()).start();
								 new Thread(new myThreadstateno()).start();
								 Toast.makeText(mContext, "请点击上传按钮强制上传！", Toast.LENGTH_LONG).show();
								 state=true;
							}
						} )  
						.setNegativeButton("否" , new OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								conSer.DelContactByConIDTrue(contactID);
								new Thread(new myThreadstate()).start();
								 new Thread(new myThreadstateno()).start();
							}
						}) ; 
						dia.show();
					}
				}
				else {
					if(type==0){
						for(ContactInfoBySqlite con:listUpdata){
							ContactInfo coninfo = writeModel(con);
							ContactInfoBLL.UpdataContact(mContext, coninfo,con.get_id());
						}
					}
			}
			}
		}
	}
}
